import requests
from bs4 import BeautifulSoup


class StockDetail:
    def __init__(self, code, name, price):
        self.code = code  # 股票代码
        self.name = name  # 股票名称
        self.price = price  # 当前价格

    def __repr__(self):
        return f"Stock(code='{self.code}', name='{self.name}', price={self.price})"


def get_stock_info(stock_code):

    stock_code = convert_stock_code(stock_code)
    url = f"https://finance.sina.com.cn/realstock/company/{stock_code}/nc.shtml"
    print(url)
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"
    }

    response = requests.get(url, headers=headers)
    response.encoding = "GBK"  # 设置编码格式

    if response.status_code == 200:
        soup = BeautifulSoup(response.text, "html.parser")

        # 获取股票名称
        stock_name = ""
        stock_name_tag = soup.find("h1", id="stockName")
        if stock_name_tag:
            # 提取股票名称
            stock_name_element = stock_name_tag.find("i", class_="c8_name")
            stock_name = stock_name_element.text.strip() if stock_name_element else None

            # 提取股票代码
            stock_code_element = stock_name_tag.find("span")
            stock_code = stock_code_element.text.strip() if stock_code_element else None

            if stock_name and stock_code:
                print(f"股票名称: {stock_name}, 股票代码: {stock_code}")
            else:
                print("股票名称或代码缺失")
        else:
            print("stock_name_tag 不存在")

        # 获取股票当前价格
        price = ""

        # 将信息封装到 Stock 对象并返回
        stock = StockDetail(stock_code, stock_name, price)
        print(f"获取到股票信息:{stock}")
        return stock
    else:
        print("无法获取数据，请检查股票代码或网络连接。")


def convert_stock_code(stock_code: str) -> str:
    """
    转换股票代码格式，例如将 '601933.SH' 转换为 'sh601933'。
    :param stock_code: 原始股票代码（格式如 '601933.SH'）
    :return: 转换后的股票代码（格式如 'sh601933'）
    """
    if not stock_code or "." not in stock_code:
        raise ValueError(f"无效的股票代码: {stock_code}")

    # 拆分代码与后缀
    code, suffix = stock_code.split(".")

    # 转换后缀为小写并拼接
    return f"{suffix.lower()}{code}"
